// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

'use strict';
const uniPush = uniCloud.getPushManager({
				appId: "__UNI__FCF68E3"
			})
const fs = require('fs');
var db;
const {
	encrypt,
	decrypt
} = require('uni-crypto')

const jwt = require('jsonwebtoken');
const secretKey = '672b32dfba1365a9c5a287f2';
function codetoken(data) {
	return new Promise((resolve, reject) => {
		try {
			const decoded = jwt.verify(data.token, secretKey);
			resolve(decoded)
			console.log("Decoded Token: ", decoded);
		} catch (err) {
			reject()
			console.error("Failed to verify token: ", err);
		}
	})
}

function retoken(data){
	return new Promise((resolve, reject) => {
		try {
			const decoded = jwt.verify(data.token, secretKey);
			var timestamp = Math.floor(Date.now() / 1000)
			if(decoded.exp - timestamp < 604800){
				gettoken(decoded._id).then(res=>{
					res.id = decoded._id
					resolve(res)
				})
			}else{
				resolve(decoded)
			}
		} catch (err) {
			 reject()
		}
	})
}


function gettoken(id){
	var uid = encrypt(id,'mysde-fc-rg-etke-ey32hacFterFDsG')
	return new Promise((resolve, reject) => {
		const payload = {
			_id:id,
			username: "exampleUser",
			role: "admin"
		};
		var token = jwt.sign(payload, secretKey, {
			expiresIn: '30days'
		})
		resolve({uid,token})
	})
}

const filePath = 'file.txt';
 function getcid(data) {
	 return new Promise((resolve, reject) => {
		 const fdata = fs.readFileSync(filePath);//读取
		 var gg = JSON.parse(fdata)
		 gg.map(item=>{
		 	if(item.id == data.id){
				resolve(item.cid)
		 		// return item.cid
		 	}
		 })
	 })
		
}



// const payload = {
//   _id: "672b36a434d099912fcb9859",
//   username: "exampleUser",
//   role: "admin"
// };
// 	var token = jwt.sign(payload, secretKey, { expiresIn: '30days' }); // Token将在1小时后过期
//  console.log("Generated Token: " + token);


// try {
//   // 验证Token
//   const decoded = jwt.verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2NzI4N2JiYTNlNWFkOTdlMjA2NTdmMzciLCJ1c2VybmFtZSI6ImV4YW1wbGVVc2VyIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNzMxMDQ5Njg1LCJleHAiOjE3MzEwNTMyODV9.5vQwoW689Sc7YiWN3hppXr2n0_nJX4R4WnvLYlTW85M', secretKey);
//   console.log("Decoded Token: ", decoded);
// } catch (err) {
//   console.error("Failed to verify token: ", err);
// }





module.exports = {
	_before: function() { // 通用预处理器

		db = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})

	},
	// async sgettoken(data){
	// 	return gettoken(data).then(res=>{
	// 		return res
	// 	}).catch(rr=>{
	// 		console.log("vvvv",rr)
	// 	})
	// },
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	async regettoken(data){
		
		return retoken(data).then((res)=>{
				
				if(res.id){
					db.collection('user').doc(res.id).update({
						data:{
							token:res.token
						}
					})
				}
			
			   return {
				code:0,
				data:res?res:''
			}
			
		  }).catch(res=>{
			return {
				code:401,
				msg:"登录过期"
			}
		  })
	},
	async registerlongin(option) {
		return await uniCloud.getPhoneNumber({
			appid: '__UNI__FCF68E3', // 替换成自己开通一键登录的应用的DCloud appid
			provider: 'univerify',
			access_token: option.access_token,
			openid: option.openid
		}).then(rres => {
			return db.collection('user').where({
				data: {
					phone: rres.phoneNumber
				}
			}).get().then(res => {
				if (res.data.length) {
					
					return gettoken(res.data[0]._id).then(ress=>{
						
						return {
							code: 0,
							data: {
								id:ress.uid,
								name: res.data[0].data.name,
								avatar: res.data[0].data.avatar,
								token: ress.token
							},
							msg: ""
						}
					})

					
				} else {
					var time = Date.now()
					return db.collection('user').add({
						data: {
							did:'', //id加密得id
							cid:option.cid,
							token:"",
							name: `d_${time}`,
							phone: rres.phoneNumber,
							avatar: "https://env-00jxhg1dwd0b.normal.cloudstatic.cn/20241106102454.png?expire_at=1730863575&er_sign=9f55e8c3a44a02d8eb5aee8c48618cec",
							create_time: time
						}
					}).then(resc => {
						console.log(resc,"jjjjn")
						if (resc.id) {
							return gettoken(resc.id).then(res=>{
								
								db.collection('user').doc(resc.id).update({
									data:{
										did:res.uid,
										token:res.token
									}
								})
								
								return {
									code: 0,
									data: {
										id:res.uid,
										token: res.token,
										name: `d_${time}`,
										avatar: "https://env-00jxhg1dwd0b.normal.cloudstatic.cn/20241106102454.png?expire_at=1730863575&er_sign=9f55e8c3a44a02d8eb5aee8c48618cec"
									},
									msg: ""
								}
							})

							
						} else {
							return {
								code: 400,
								data: [],
								msg: ""
							}
						}
					}).catch(res => {
						return {
							code: 400,
							data: [],
							msg: ""
						}
					})
				}
			})
		})
	},
	
	async getuser(id) {
		return await db.collection('user').doc(id).get().then(res => {
			return res
		})
	},
	async adduser(data) {
		
		
		
		if(data.id.length>11){
			data.id = decrypt(data.id,'mysde-fc-rg-etke-ey32hacFterFDsG')
		}
		
		
		return await db.collection('user').where(`data.phone=='${data.id}'||_id=='${data.id}'`).field("data.avatar,data.cid,data.did,data.name,data.cid").get({getOne:true}).then(res => {
			console.log(res,"bbb",data)
			
			 getcid({id:res.data.data.did}).then(ress=>{
				 
				 console.log(ress,"aaaa")
				 
				  uniPush.sendMessage({
					"push_clientid": ress,
					"title": "",
					"content": "",
					"payload": {
						user:{
						  did:data.did,
						  avatar:data.avatar,
						  name:data.name,
						  time:Date.now(),
						  tuser:res.data.data
						},
						"type":"add",
					}
				})
			})
			
		})
		
		 //return encrypt('672b32dfba1365a9c5a287f2','mysde-fc-rg-etke-ey32hacFterFDsG')  加密
		//return decrypt('d6188cdeb723be6c3f81cd56c014c01b1f76deedcf76b852677515e95277dc1d','mysde-fc-rg-etke-ey32hacFterFDsG')   解密
	},
	async setcid(data) {
		
		// fs.unlink(filePath, (err) => {
		//   if (err) throw err;
		//   console.log('文件已删除');
		// })
		// return 0
		
		 try {
			fs.accessSync(filePath, fs.constants.F_OK | fs.constants.R_OK);
		 	const fdata = fs.readFileSync(filePath);//读取
			var gg = JSON.parse(fdata)
			
			gg.unshift({
				id:data.id,
				cid:data.cid
			})
			
			 fs.writeFileSync(filePath, JSON.stringify(gg));
			
			 // const fata = fs.readFileSync(filePath);//读取
			 
			 // var ggs = JSON.parse(fata)
			 // console.log(ggs)
			 
		 	return {
				code:0
			}
			
		 } catch (error) {
			 var oobj = [{
			 	id:data.id,
			 	cid:data.cid
			 }]
			 fs.writeFileSync(filePath, JSON.stringify(oobj))
			
		}
	},
	async getcid(data) {
		const fdata = fs.readFileSync(filePath);//读取
		var gg = JSON.parse(fdata)
		gg.map(item=>{
			if(item.id == data.id){
				return item.cid
			}
		})
	},
	
	async addfriend(item){
		
		return await getcid({id:item.did}).then(cid=>{
			item.msg = '我通过了你的验证，现在可以聊天了'
			item.ismag = 1
			return  uniPush.sendMessage({
				"push_clientid": cid,
				"title": "",
				"content": "",
				"payload": {
					user:item,
					"type":"friend",
				}
			}).then(res=>{
				
				return db.collection('friend').add({
					data: item
				})
				
			})
			
		})
		
	},
	
}